/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sinemaproject;

import entity.Calisan;
import entity.Calisantip;
import entity.Filmtipleri;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author admin
 */
public class CalisanIslemi extends javax.swing.JFrame {

    /**
     * Creates new form Calisan
     */
    public CalisanIslemi() {
        initComponents();
        refreshCalisanIslemiUITable();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jTextField6 = new javax.swing.JTextField();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Kullanici Adi", "Sifre", "Ad", "Soyad", "Dogum Tarihi", "Giris Tarihi"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable2.setFocusable(false);
        jTable2.getTableHeader().setReorderingAllowed(false);
        jTable2.setUpdateSelectionOnSort(false);
        jTable2.setVerifyInputWhenFocusTarget(false);
        jTable2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable2MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable2);

        jTextField1.setText("Kullanici Adi");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jButton1.setText("Ekle");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Güncelle");
        jButton2.setEnabled(false);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Sil");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jTextField2.setText("Sifre");

        jTextField3.setText("Dogum Tarihi");

        jTextField4.setText("Ad");

        jTextField5.setText("Soyad");

        jTextField6.setText("Giris Tarihi");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 712, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                            .addComponent(jTextField4))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField2)
                            .addComponent(jTextField5, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE)
                            .addComponent(jTextField6))
                        .addGap(18, 18, 18)
                        .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addGap(14, 14, 14)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE)
                            .addComponent(jTextField1)
                            .addComponent(jTextField2))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                            .addComponent(jTextField6)
                            .addComponent(jTextField5))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(33, 33, 33))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
  private EntityManagerFactory emf;
    private DefaultTableModel tmodel;
    private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked
        int row = jTable2.getSelectedRow();

        
        
        DateFormat formatter ; 
          
        formatter = new SimpleDateFormat("dd-MM-yy");
  
  
  
        jTextField1.setText((String) jTable2.getValueAt(row, 1));
        jTextField2.setText((String) jTable2.getValueAt(row, 2));
        jTextField3.setText( (String)jTable2.getValueAt(row, 5));
        jTextField4.setText((String) jTable2.getValueAt(row, 3));
        jTextField5.setText((String) jTable2.getValueAt(row, 4));
        jTextField6.setText((String) jTable2.getValueAt(row, 6));
        
        

        jButton2.setEnabled(true);
        jButton3.setEnabled(true);
    }//GEN-LAST:event_jTable2MouseClicked

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed
        public boolean addcalisan(Calisan calis) {
      EntityManager em = getEntityManager();
       try{
         em.getTransaction().begin();
         em.persist(calis); 
         em.getTransaction().commit();
       } finally {
        em.close();
        return false;
       }
    }  
    public List<Calisan> getAllCalisan(){        
        
        /////////////
        List<Calisantip> tips;        
        EntityManager em = getEntityManager();
        try{
            em.getTransaction().begin();
            tips = em.createNamedQuery("Calisantip.findAll").getResultList();
        } finally {
            em.close();
        }  
        
        for( Calisantip tip : tips ){
            jComboBox1.addItem(tip.getTipAd());
        }
        //////////////////
        
        List<Calisan> tips2;        
        EntityManager em2 = getEntityManager();
        try{
            em2.getTransaction().begin();
            tips2 = em2.createNamedQuery("Calisan.findAll").getResultList();
        } finally {
            em2.close();
        }    
        
        return tips2;  
        
               
    }
    
    public void refreshCalisanIslemiUITable(){
        
        List<Calisan> tips;
        tips = getAllCalisan();
        
        tmodel = (DefaultTableModel) jTable2.getModel();
        //clean tmodel...
        tmodel.setRowCount(0);
        DateFormat formatter ; 
        formatter = new SimpleDateFormat("dd-MM-yy");

        
        for(Calisan tip : tips){
            //System.out.println(tip.getTipIsmi());
            tmodel.addRow(new Object[]{tip.getIdCalisan(), tip.getSistemIsim(), tip.getSistemSifre(),tip.getAd(),tip.getSoyad(),formatter.format(tip.getDogumTarihi()),formatter.format(tip.getIseGiris())});
        }

        jTable2.setModel(tmodel);
    }  
    private Calisantip getTipByname(String selectedItem) {
        
        Calisantip tip;        
        EntityManager em = getEntityManager();
        try{
            em.getTransaction().begin();
            tip = (Calisantip) em.createNamedQuery("Calisantip.findByTipAd").setParameter("tipAd", selectedItem).getSingleResult();
        } finally {
            em.close();
        }                
        return tip;          
    } 
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        Calisan yeniTip = new Calisan();
        DateFormat formatter ; 
        formatter = new SimpleDateFormat("dd-MM-yy");
        
        
        yeniTip.setSistemIsim(jTextField1.getText());
        yeniTip.setSistemSifre(jTextField2.getText());
        try {
            yeniTip.setDogumTarihi((Date)formatter.parse(jTextField3.getText()));
        } catch (ParseException ex) {
            Logger.getLogger(CalisanIslemi.class.getName()).log(Level.SEVERE, null, ex);
        }
        yeniTip.setAd(jTextField4.getText());
        yeniTip.setSoyad(jTextField5.getText());
        
        
        
        
        ///////////////////////////
        Calisantip ctip3 = getTipByname(jComboBox1.getSelectedItem().toString() );
        
        
        
        
        yeniTip.setCalisanTipId(ctip3);
        try {
            yeniTip.setIseGiris((Date)formatter.parse(jTextField6.getText()));
        } catch (ParseException ex) {
            Logger.getLogger(CalisanIslemi.class.getName()).log(Level.SEVERE, null, ex);
        }
                                                               
        addcalisan(yeniTip);
        refreshCalisanIslemiUITable();




    }//GEN-LAST:event_jButton1ActionPerformed
    private EntityManager getEntityManager() {
    if (emf == null) {
            emf = Persistence.createEntityManagerFactory("SinemaProjectPU");
    }
        return emf.createEntityManager();
    }
    public boolean addCalisanIslemi(CalisanIslemi calisan) {
      EntityManager em = getEntityManager();
       try{
         em.getTransaction().begin();
         em.persist(calisan); 
         em.getTransaction().commit();
       } finally {
        em.close();
        return false;
       }
    }  
    
    
    
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        
        int row = jTable2.getSelectedRow();
        Calisan cTip = new Calisan();
        cTip.setIdCalisan((Integer) jTable2.getValueAt(row, 0));
        cTip.setSistemIsim(jTextField1.getText());
        cTip.setSistemSifre(jTextField2.getText());
        
        DateFormat formatter ; 
        formatter = new SimpleDateFormat("dd-MM-yy");
        try {
            cTip.setDogumTarihi((Date)formatter.parse(jTextField3.getText()));
        } catch (ParseException ex) {
            Logger.getLogger(CalisanIslemi.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        cTip.setAd(jTextField4.getText());
        cTip.setSoyad(jTextField5.getText());
                        
         try {
            cTip.setIseGiris((Date)formatter.parse(jTextField6.getText()));
        } catch (ParseException ex) {
            Logger.getLogger(CalisanIslemi.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
    
        updateCalisanIslemi(cTip);
        refreshCalisanIslemiUITable();

        jButton2.setEnabled(false);
        jButton3.setEnabled(false);
    }//GEN-LAST:event_jButton2ActionPerformed
      public boolean updateCalisanIslemi(Calisan ctip) {
      EntityManager em = getEntityManager();
      try{
        em.getTransaction().begin();
        Calisan tipx = em.find(Calisan.class, ctip.getIdCalisan());
        
        
        tipx.setSistemIsim(ctip.getSistemIsim());
        tipx.setSistemSifre(ctip.getSistemSifre());
        tipx.setDogumTarihi(ctip.getDogumTarihi());
        tipx.setAd(ctip.getAd());
        tipx.setSoyad(ctip.getSoyad());
        tipx.setIseGiris(ctip.getIseGiris());
        
        
        em.getTransaction().commit();
      } finally {
        em.close();
        return false;
      }

    }  
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed

        // TODO add your handling code here:
        int row = jTable2.getSelectedRow();
        Calisan ctip = new Calisan();
        ctip.setIdCalisan((Integer) jTable2.getValueAt(row, 0));

        removeCalisan(ctip);
        refreshCalisanIslemiUITable();

        jButton2.setEnabled(false);
        jButton3.setEnabled(false);




    }//GEN-LAST:event_jButton3ActionPerformed
    public boolean removeCalisan(Calisan cTip) {
      EntityManager em = getEntityManager();
      try{
        em.getTransaction().begin();
        Calisan tipx = em.find(Calisan.class, cTip.getIdCalisan());
        em.remove(tipx);
        em.getTransaction().commit();
      } finally {
        em.close();
        return false;
      }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CalisanIslemi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CalisanIslemi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CalisanIslemi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CalisanIslemi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CalisanIslemi().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration//GEN-END:variables
}
